//
//  MYGResumeEditEndViewController.swift
//  MYDoctor
//
//  Created by 小火科技 on 2024/4/12.
//

import UIKit
import BRPickerView
import IQKeyboardManagerSwift

class MYGResumeEditEndViewController: MYGBaseController {
    
    var skills:[MYGResumType]?{
        didSet {
            guard let arr = skills else {return}
   
        }
        
    }
    private var selectIndex:Int = 0//选择的是哪一个模块
    private var contents: [Any] = []
    var image: UIImage?
    private var tipName:String = ""

    private var Honors:[Any] = []
    private var Patent:[Any] = []
    private var Publish:[Any] = []
    private var Clinical:[Any] = []
    private var GoodAt:[Any] = []
    private var Custom:[Any] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
        topView.setPace(index: 4)
    }
    //
    func configData(type:String,name:String) {
        contents.removeAll()
        tipName = name
        for item in skills! {
            let modelName = item.modelName
            
            if (modelName == type){
                for dict in item.list {
                    var items: [Any] = []
                    let nameItem = MYGChangeEnterMessageTextCellModel()
                    nameItem.name = "\(name)名称"
                    nameItem.placeholder = "请输入"
                    nameItem.isRequeired = false
                    nameItem.key = "\(dict.id)"
                    nameItem.content = type == "GoodAt" ? dict.content : dict.title
                    items.append(nameItem)
                    
                    let startItem = MYGChangeEnterMessageTextCellModel()
                    startItem.name = "开始时间"
                    startItem.placeholder = "请输入开始时间"
                    startItem.isRequeired = false
                    startItem.canEdit = false
                    if type == "GoodAt" {
                        let created_at = dict.created_at.double()
                        startItem.content = "\(created_at?.toTimeString(formatter:"yyyy-MM-dd") ?? "")"
                    }else {
                        startItem.content = dict.dateStart
                    }
                    startItem.clickAction = {[weak startItem, weak self] in
                        IQKeyboardManager.shared.resignFirstResponder()
                        guard let dateItem = startItem, let self = self else {
                            return
                        }
                        BRDatePickerView.showDatePicker(with: .YMD, title: "请选择日期", selectValue: "") { _, date in
                            dateItem.content = date ?? ""
                            self.tableView.reloadData()
                        }
                    }
                    items.append(startItem)
                    
                    let endItem = MYGChangeEnterMessageTextCellModel()
                    endItem.name = "结束时间"
                    endItem.placeholder = "请输入结束时间"
                    endItem.isRequeired = false
                    endItem.canEdit = false
                    if type == "GoodAt" {
                        let created_at = dict.created_at.double()
                        endItem.content = "\(created_at?.toTimeString(formatter:"yyyy-MM-dd") ?? "")"
                    }else {
                        endItem.content = dict.dateEnd
                    }
                    
                    endItem.clickAction = {[weak endItem, weak self] in
                        IQKeyboardManager.shared.resignFirstResponder()
                        guard let dateItem = endItem, let self = self else {
                            return
                        }
                        BRDatePickerView.showDatePicker(with: .YMD, title: "请选择日期", selectValue: "") { _, date in
                            dateItem.content = date ?? ""
                            self.tableView.reloadData()
                        }
                    }
                    items.append(endItem)
                    contents.append(items)
                }
                break
            }
            
        }
        

    }
    
    // MARK: - Cell
     func configCell(_ index:Int) {
         selectIndex = index
         headerView.index = index
        switch index {
        case 0:
            if Honors.count > 0 {
                contents = Honors
            }else {
                configData(type: "Honors", name: "荣誉")
                Honors = contents
            }
         
        case 1:
            if Patent.count > 0 {
                contents = Patent
            }else {
                configData(type: "Patent", name: "专利")
                Patent = contents
            }
        case 2:
            if Publish.count > 0 {
                contents = Publish
            }else {
                configData(type: "Publish", name: "出版")
                Publish = contents
            }
            
        case 3:
            if Clinical.count > 0 {
                contents = Clinical
            }else {
                configData(type: "Clinical", name: "文献")
                Clinical = contents
            }
        case 4:
            if GoodAt.count > 0 {
                contents = GoodAt
            }else {
                configData(type: "GoodAt", name: "专业擅长")
                GoodAt = contents
            }
        case 5:
            if Custom.count > 0 {
                contents = Custom
            }else {
                configData(type: "Custom", name: "自定义")
                Custom = contents
            }
        default:
            break
        }
         
         tableView.reloadData()
    }
    
    // MARK: - UI
    private func configUI() {
        title = "编辑简历"
        
        view.backgroundColor = .white
        view.addSubview(tableView)
        view.addSubview(saveButton)
        view.addSubview(headerView)
        view.addSubview(topView)
        
        topView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.right.equalToSuperview()
            make.height.equalTo(18.5)
        }
        headerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(topView.snp.bottom).offset(22)
            make.height.equalTo(222)
        }
    
        tableView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(saveButton.snp.top)
        }
        
        saveButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(bottomSafeheight)
            make.height.equalTo(49)
        }
    }
    
    // MARK: - lazy load
    private lazy var topView:MYGResumePaceView = {
        let topV = MYGResumePaceView()
        return topV
    }()
    
    private lazy var headerView:MYGResumeEditEducationView = {
        let header = MYGResumeEditEducationView()
        header.selectTypeBlock = { [self] value in
            selectIndex = value
            configCell(value)
        }
        return header
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRectZero, style: .grouped)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(cellWithClass: MYGChangeEnterMessageTitleCell.self)
        return tableView
    }()
    
    private lazy var saveButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("确定", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .medium(17)
        //btn.backgroundColor = .rgba(162, 146, 254, 1)
        btn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))
        btn.addTarget(self, action: #selector(save), for: .touchUpInside)
        return btn
    }()

}
// MARK: - APi
extension MYGResumeEditEndViewController {
    
    func getSubmotData(arrs: [Any],modelName:String)-> [String:Any]{
        var arr:[[String: String]] = [[:]]
        // 如果多个 contents里面就会包含 不止4个 要把区分出来 4个为单位
        arr.removeAll()
        for subItem in arrs {
            var params: [String: String] = [:]
            for (index, item) in (subItem as! NSArray).enumerated() {
                if let item = item as? MYGChangeEnterMessageTextCellModel {
                    switch index {
                    case 0:
                        if modelName == "GoodAt" {
                            params["content"] = item.content
                            params["title"] = item.content
                        }else {
                            params["title"] = item.content
                        }
                        if(!item.key.isEmpty){
                            params["id"] = item.key
                        }
                    case 1:
                        params["dateStart"] = item.content
                    case 2:
                        params["dateEnd"] = item.content
                    default:
                        break
                    }
                }
            }
            arr.append(params)
        }
        
        var content:[String:Any] = [:]
        content["modelName"] = modelName
        content["list"] = arr
        content["index"] = modelName
        
        return content
    }
    @objc
    private func save() {
        let ho = getSubmotData(arrs: Honors, modelName: "Honors")
        let pa = getSubmotData(arrs: Patent, modelName: "Patent")
        let pu = getSubmotData(arrs: Publish, modelName: "Publish")
        let cl = getSubmotData(arrs: Clinical, modelName: "Clinical")
        let go = getSubmotData(arrs: GoodAt, modelName: "GoodAt")
        let cu = getSubmotData(arrs: Custom, modelName: "Custom")
        
//        var arr:[[String: String]] = [[:]]
//        // 如果多个 contents里面就会包含 不止4个 要把区分出来 4个为单位
//        arr.removeAll()
//        for subItem in contents {
//            var params: [String: String] = [:]
//            for (index, item) in (subItem as! NSArray).enumerated() {
//                if let item = item as? MYGChangeEnterMessageTextCellModel {
//                    switch index {
//                    case 0:
//                        params["title"] = item.content
//                        if(!item.key.isEmpty){
//                            params["id"] = item.key
//                        }
//                    case 1:
//                        params["dateStart"] = item.content
//                    case 2:
//                        params["dateEnd"] = item.content
//                    default:
//                        break
//                    }
//                }
//            }
//            arr.append(params)
//        }
//        
//        var name = ""
//        switch selectIndex {
//        case 0:
//           name = "Honors"
//        case 1:
//            name = "Patent"
//        case 2:
//            name = "Publish"
//        case 3:
//            name = "Clinical"
//        case 4:
//            name = "GoodAt"
//        case 5:
//            name = "Custom"
//        default:
//            break
//        }

        var params:[String:Any] = [:]
        params["doctor"] = [:]
        
//        var content:[String:Any] = [:]
//        content["modelName"] = name
//        content["list"] = arr
//        content["index"] = ""
        
        params["extModel"] = [ho,pa,pu,cl,go,cu]
        
        saveApi(taget:.editMineResum(param: params))
    }
    //保存
    private func saveApi(taget: MYGResumeApi ){
        MYGLoading.show()
        MMYGNetwork<MYGResumeApi,MYGEmptyModel>.request(target: taget) { _ in
            MYGLoading.hide()
            MMYGHUD.showToast(text: "保存成功"){
                // 确保导航控制器存在且B页面已入栈
                guard let bViewController = self.navigationController?.viewControllers.first(where: { $0 is MYGResumeViewController }) else {
                    print("BViewController not found in the navigation stack.")
                    return
                }
                // 使用popToViewController方法直接返回到B页面
                self.navigationController?.popToViewController(bViewController, animated: true)
            }
            
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }

}
extension MYGResumeEditEndViewController {
    // MARK: -  删除简历某一项
    @objc private func  delResumecontent(_ sender:UIButton) {
        let tag = sender.tag
        contents.remove(at: tag)
        tableView.reloadData()
        getData()
    }
    
    @objc func clickButton() {
        
        var items: [Any] = []
        let nameItem = MYGChangeEnterMessageTextCellModel()
        nameItem.name = "\(tipName)名称"
        nameItem.placeholder = "请输入"
        nameItem.isRequeired = false
        items.append(nameItem)
        
        let startItem = MYGChangeEnterMessageTextCellModel()
        startItem.name = "开始时间"
        startItem.placeholder = "请输入开始时间"
        startItem.isRequeired = false
        startItem.canEdit = false
        startItem.clickAction = {[weak startItem, weak self] in
            IQKeyboardManager.shared.resignFirstResponder()
            guard let dateItem = startItem, let self = self else {
                return
            }
            BRDatePickerView.showDatePicker(with: .YMD, title: "请选择日期", selectValue: "") { _, date in
                dateItem.content = date ?? ""
                self.tableView.reloadData()
            }
        }
        items.append(startItem)
        
        let endItem = MYGChangeEnterMessageTextCellModel()
        endItem.name = "结束时间"
        endItem.placeholder = "请输入结束时间"
        endItem.isRequeired = false
        endItem.canEdit = false
        endItem.clickAction = {[weak endItem, weak self] in
            IQKeyboardManager.shared.resignFirstResponder()
            guard let dateItem = endItem, let self = self else {
                return
            }
            BRDatePickerView.showDatePicker(with: .YMD, title: "请选择日期", selectValue: "") { _, date in
                dateItem.content = date ?? ""
                self.tableView.reloadData()
            }
        }
        items.append(endItem)
        contents.append(items)
        tableView.reloadData()
        getData()
    }
    
    private func getData(){
        switch selectIndex {
        case 0:
            Honors = contents
        case 1:
            Patent = contents
        case 2:
            Publish = contents
        case 3:
            Clinical = contents
        case 4:
            GoodAt = contents
        case 5:
            Custom = contents
        default:
            break
            
        }
    }
 
//    private func getString()->String {
//        switch selectIndex {
//        case 0:
//            return "Honors"
//        case 1:
//            return "Patent"
//        case 2:
//            return "Publish"
//        case 3:
//            return "Clinical"
//        case 4:
//            return "GoodAt"
//        case 5:
//            return "Custom"
//        default:
//            break
//        }
//    }
    
}
extension MYGResumeEditEndViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        contents.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let arr:NSArray = contents[section] as! NSArray
        return arr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        65
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let arr:[Any] = contents[indexPath.section] as! [Any]
        if let item = arr[indexPath.row] as? MYGChangeEnterMessageTextCellModel {
            let cell = tableView.dequeueReusableCell(withClass: MYGChangeEnterMessageTitleCell.self, for: indexPath)
            cell.model = item
            return cell
        }
        
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: Int(screenWidth), height: 30))
        
        let line = UIView()
        line.backgroundColor = .rgba(73, 117, 236, 1)
        v.addSubview(line)
        
        let tipLab = UILabel()
        tipLab.text = "教育经历"
        tipLab.textColor = .rgba(34, 34, 34, 1)
        tipLab.font = .medium(18)
        
        v.addSubview(tipLab)
        line.snp.makeConstraints { make in
            make.left.equalTo(17.5)
            make.height.equalTo(15)
            make.width.equalTo(3)
            make.top.equalToSuperview().offset(17.5)
        }
        
        tipLab.snp.makeConstraints { make in
            make.centerY.equalTo(line)
            make.left.equalTo(line.snp.right).offset(13)
            make.height.equalTo(25)
        }
        let list = self.skills![section]
        let type = list.modelName
        switch selectIndex {
        case 0:
            tipLab.text = "荣誉"
        case 1:
            tipLab.text = "专利"
        case 2:
            tipLab.text = "出版"
        case 3:
            tipLab.text = "文献"
        case 4:
            tipLab.text = "专业擅长"
        case 5:
            tipLab.text = "自定义"
        default:
            break
        }
        
        if section == 0 {
            let addBtn = UIButton()
            addBtn.setImage(UIImage(named: "icon_tianjia"), for: .normal)
            addBtn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            v.addSubview(addBtn)
            addBtn.snp.makeConstraints { make in
                make.top.bottom.right.equalToSuperview()
                make.width.equalTo(44)
            }
            
        }else {
            let btn = UIButton()
            btn.setImage(UIImage(named: "re_del"), for: .normal)
            btn.addTarget(self, action: #selector(delResumecontent(_:)), for: .touchUpInside)
            v.addSubview(btn)
            btn.tag = section
            btn.snp.makeConstraints { make in
                make.top.bottom.right.equalToSuperview()
                make.width.equalTo(44)
            }
        }
        
        return v
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        30
    }
  
}

//{
//    contents = []
//    for item in skills! {
//        let type = item.modelName
//        var name:String = ""
//        if (type == "GoodAt"){// 专业擅长
//            name = "专业擅长"
//        }else if (type == "Honors"){//个人荣誉
//            name = "个人荣誉"
//        }else if (type == "Clinical"){//临床实验
//            name = "临床实验"
//        }else if (type == "Internship"){//实习经验
//            name = "实习经验"
//        } else if (type == "Publish"){//出版
//            name = "出版"
//        }else if (type == "Patent"){//获得专利
//            name = "获得专利"
//        } else if (type == "Custom"){//自定义模块
//            name = "自定义"
//        }
//        for dict in item.list {
//            var arr:[Any] = []
//            let nameItem = MYGChangeEnterMessageTextCellModel()
//            nameItem.name = name
//            nameItem.placeholder = "请输入"
//            nameItem.isRequeired = false
//            if (dict["title"] != nil) {
//                nameItem.content = dict["title"]!
//            }
//            nameItem.canEdit = false
//            arr.append(nameItem)
//            
//            let startItem = MYGChangeEnterMessageTextCellModel()
//            startItem.name = "开始时间"
//            startItem.placeholder = "请输入开始时间"
//            startItem.isRequeired = false
//            arr.append(startItem)
//            
//            let endItem = MYGChangeEnterMessageTextCellModel()
//            endItem.name = "结束时间"
//            endItem.placeholder = "请输入结束时间"
//            endItem.isRequeired = false
//            arr.append(endItem)
//            
//            contents.append(arr)
//        }
//        
//    }
//}
